import 'package:flutter/material.dart';
import 'i_model.dart';
import 'package:flutter/rendering.dart';
import 'package:pull_to_refresh/pull_to_refresh.dart';

abstract class IListModel<T> extends IModel<List<T>> {
  // 当前页
  int _page = 1;
  // 页数据长度
  int _size = 20;
  // 是否加载完全部
  bool _isLoadAll = false;

  // 下拉刷新控制器
  RefreshController _refreshController = RefreshController();

  // 获取当前页
  int getPage() {
    return _page;
  }

  // 获取页数据长度
  int getSize() {
    return _size;
  }

  //设置size
  void setSize(int size) {
    this._size = size;
  }

  // 是否加载完全部
  bool isLoadAll() {
    return _isLoadAll;
  }

  void setLoadAll(bool all) {
    _isLoadAll = all;
  }

  // 获取分页信息
  Map<String, dynamic> getPagination() {
    return {"page": getPage(), "size": getSize()};
  }

  /// 获取下拉刷新控制器
  RefreshController getRefreshController() {
    return _refreshController;
  }

  @override
  Future<void> requestData() async {
    if (isLoadAll()) {
      return;
    }
    setFirstLoad(false);
    setLoadFail(false);
    setRequestDone(false);
    notifyListeners();
    try {
      List<T> data = await request();
      if (data.length == 0) {
        setLoadAll(true);
      } else {
        if (_page == 1) {
          setData(data);
        } else {
          getData()?.addAll(data);
        }
        _page++;
      }
    } catch (e) {
      setLoadFail(true);
    }
    setRequestDone(true);
    notifyListeners();
  }

  Future<void> refresh() async {
    if (isRequestDone()) {
      _page = 1;
      setLoadAll(false);
      return await requestData();
    }
  }

  Future<void> loadMore() async {
    if (!isRequestDone()) {
      return;
    }
    return await requestData();
  }

  @override
  bool isEmpty() {
    return super.isEmpty() || getData()?.length == 0;
  }

  /// 滚动至顶部
  void scrollTop() {
    BuildContext? context = getContext();
    if (context != null) {
      RenderSliver? renderSliver =
          context.findAncestorRenderObjectOfType<RenderSliver>();
      if (renderSliver != null && renderSliver.constraints.overlap > 0) {
        Scrollable.ensureVisible(context);
      }
    }
  }
}
